package com.mate.cloud.gateway.predicate;

import com.mate.cloud.gateway.config.LearnBetweenRouteConfig;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 此谓词匹配在 之后和之前发生的请求
 *
 * @author cong zhi
 * @email 448341911@qq.com
 * @createDate 2023/3/14 18:13
 * @version: v1.0
 */
@Component(value = "LearnBetween")
public class LearnBetweenRouteFactory extends AbstractRoutePredicateFactory<LearnBetweenRouteConfig> {


    public LearnBetweenRouteFactory() {
        super(LearnBetweenRouteConfig.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("begin", "end");
    }

    @Override
    public Predicate<ServerWebExchange> apply(LearnBetweenRouteConfig config) {
        // 获取配置文件中的配置值
        LocalDateTime begin = config.getBegin();
        LocalDateTime end = config.getEnd();
        // lambda
        return serverWebExchange -> {
             LocalDateTime now = LocalDateTime.now();
            return now.isAfter(begin) && now.isBefore(end);
        };
    }

    public static void main(String[] args) {
        System.out.println( DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).format(LocalDateTime.now()));
    }
}
